package opensource.web.util.configure;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 配置读取类<p>
 * 配置文件格式<p>
 * 1. 配置项书写格式有如下三种<p>
 * ---- 1) key = value<p>
 * ---- 2) key=value<p>
 * ---- 3) key1 = value1  key2 = value2<p>
 * 2. key由数字和字母构成<p>
 * 3. value由数字字母以及允许包含 . : \ 这三种标点<p>
 * 4. ; 为注释标记，可以出现在行首(表示注释正行, 允许注释记号前后空格)，
 * 也可以出现在配置项后面(表示对该项配置说明, 从标记位置开始到行末为注释内容)<p>
 * 
 * @author ming
 * @version 0.2
 * 
 */
public class Configure {
	private File conf;
	private final String GUOTEIGNORE = ";";    // 配置文件中的注释符, --V0.1版本: 仅支持空行注释(注释符号钱允许空格)
	private final String GUOTEQUAL = "="; 
	private final String REGEX = "[a-z|A-Z|0-9|]{1,}(\\s)*=(\\s)*([a-z|A-Z|0-9]|:|\\\\|.){1,}(\\s)*";
	private HashMap<String, String> confMap = new HashMap<String, String>();
	
	public Configure(File file) {
		conf = file;
	}
	
	public Configure(String fileName) {
		conf = new File(fileName);
	}
	
	/**
	 * 获取 包含配置项的HashMap
	 * 
	 * @return HashMap
	 */
	public HashMap<String, String> GetConfigure() {
		String line = null;
		Pattern pat = Pattern.compile(REGEX);
		if (conf.canRead()) {
			try {
				BufferedReader read = new BufferedReader(new FileReader(conf));
				while (true) {
					line = read.readLine();
					
					if (line == null) {
						break;
					}
						
					line = line.trim();
					// 为注释行或者空行
					if (line.startsWith(GUOTEIGNORE) || line.length() == 0) {
						continue ;
					}
					// 一行中若存在注释符，则取注释符前的内容
					if (line.contains(GUOTEIGNORE)) {
						line = line.substring(0, line.indexOf(GUOTEIGNORE) - 1);
					}
					
					Matcher mat = pat.matcher(line);
					while (mat.find()) {
						AddItem(mat.group(0));
					}
				}
				read.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return confMap;
	}
	
	/**
	 * 把配置文件中符合规则的配置加到HashMap中
	 * @param pat
	 */
	private void AddItem(String pat) {
		String key = null, value = null;
		final int pos = pat.indexOf(GUOTEQUAL);
		
		key = pat.substring(0, pos - 1).trim();
		value = pat.substring(pos + 1, pat.length()).trim();
		confMap.put(key, value);
	}
}
